package com.example.user_management_sys.controller;

import com.example.user_management_sys.model.UserInfo;
import com.example.user_management_sys.service.UserService;

import com.example.user_management_sys.util.ConstVariable;
import com.example.user_management_sys.util.PasswordUtil;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

@RestController
public class UserController {

    @Resource
    private UserService userService;

    // 登录方法
    @RequestMapping("/login")
    public boolean login(HttpServletRequest request, String loginname, String password) {
        if (StringUtils.hasLength(loginname) && StringUtils.hasLength(password)) {
            // 参数有效
            UserInfo userInfo = userService.getUserByLoginName(loginname);
            if (userInfo != null && userInfo.getUid() > 0) {
                // 数据库中的加密方法
                String dbPassword = userInfo.getPassword();
                boolean result = PasswordUtil.decrypt(password,dbPassword);
                if(result){
                    // 存储session
                    HttpSession session = request.getSession(true);
                    session.setAttribute(ConstVariable.USERINFO_SESSION_KEY, userInfo);
                    return true;
                }
            }
        }
        return false;
    }

    // 查询所有列表（未分页）
    @RequestMapping("/list")
    public List<UserInfo> getAll() {
        return userService.getAll();
    }

    // 查询所有列表 (带分页和条件查询)
    @RequestMapping("/listbypage")
    public HashMap<String, Object> getListByPage(String username,
                                                 String address,
                                                 String email,
                                                 Integer pageindex,
                                                 Integer pagesize) {
        HashMap<String, Object> result = new HashMap<>();
        if (pageindex == null || pageindex < 1) {
            pageindex = 1;
        }
        if (pagesize == null || pagesize <= 0) {
            pagesize = 2;
        }
        if (!StringUtils.hasLength(username)) {
            username = null;
        }
        if (!StringUtils.hasLength(address)) {
            address = null;
        }
        if (!StringUtils.hasLength(email)) {
            email = null;
        }
        int offset = (pageindex - 1) * pagesize;
        List<UserInfo> list = userService.getListByPage(username, address, email, pagesize, offset);
        int totalCount = userService.getListByPageCount(username, address, email);
        result.put("list", list);
        result.put("count1", totalCount);
        System.out.println(offset);
        return result;
    }


    @RequestMapping("/add")
    public int add(UserInfo userInfo, HttpServletRequest request) {
        int result = 0;
        // 1.非空校验
        if (userInfo == null || !StringUtils.hasLength(userInfo.getUsername()) ||
                !StringUtils.hasLength(userInfo.getLoginname()) ||
                !StringUtils.hasLength(userInfo.getPassword())) return result;
        // 2.判断必须为超级管理员，才能进行添加操作
        HttpSession session = request.getSession(false);
        if (session == null || session.getAttribute(ConstVariable.USERINFO_SESSION_KEY) == null) return result;
        UserInfo loginUser = (UserInfo) session.getAttribute(ConstVariable.USERINFO_SESSION_KEY);
        if (loginUser.isIsadmin() == false) return result;
        // 3.对登录名作唯一校验
        UserInfo loginNameUser = userService.getUserByLoginName(userInfo.getLoginname());
        // 当前登录名是否存在的判断
        if (loginNameUser != null && loginNameUser.getUid() > 0) return result;
        // 4.添加用户到操作数据库
        userInfo.setPassword(PasswordUtil.encrypt(userInfo.getPassword())); // 加密密码
        result = userService.add(userInfo);
        return result;
    }

    @RequestMapping("getuserbyid")
    public UserInfo getUserById(Integer uid) {
        UserInfo userInfo = null;
        // 1.非空校验
        if (uid == null || uid <= 0) return userInfo;
        // 2.查询数据库
        userInfo = userService.getUserByUid(uid);
        // 3.将密码隐藏掉
        userInfo.setPassword("");
        return userInfo;
    }

    @RequestMapping("/update")
    public int update(UserInfo userInfo, HttpServletRequest request) {
        int result = 0;
        // 1.非空校验
        if (userInfo == null || userInfo.getUid() < 0 ||
                !StringUtils.hasLength(userInfo.getUsername())) return result;
        // 2.判断必须为超级管理员，才能进行添加操作
        HttpSession session = request.getSession(false);
        if (session == null || session.getAttribute(ConstVariable.USERINFO_SESSION_KEY) == null) return result;
        UserInfo loginUser = (UserInfo) session.getAttribute(ConstVariable.USERINFO_SESSION_KEY);
        if (loginUser.isIsadmin() == false) return result;
        // 3.添加用户到操作数据库
        if(StringUtils.hasLength(userInfo.getPassword())){
            // 对密码进行加密
            userInfo.setPassword(PasswordUtil.encrypt(userInfo.getPassword()));
        }
        result = userService.update(userInfo);
        return result;

    }

    @RequestMapping("/del")
    public int del(Integer uid) {
        if (uid == null) return 0;
        int result = 0;
        result = userService.del(uid);
        return result;

    }

    @RequestMapping("/delbyids")
    public int dels(String ids, HttpServletRequest request) {
        if (!StringUtils.hasLength(ids)) return 0;
        System.out.println(ids);
        String[] idsArr = ids.split(",");
        if (idsArr == null || idsArr.length <= 0) return 0;
        List<Integer> idsList = new ArrayList<>();
        // 得到当前登录用户的id
        HttpSession session = request.getSession(false);
        if (session == null || session.getAttribute(ConstVariable.USERINFO_SESSION_KEY) == null) return 0;
        int uid = ((UserInfo) session.getAttribute(ConstVariable.USERINFO_SESSION_KEY)).getUid();
        for (String item : idsArr) {
            if (StringUtils.hasLength(item)) {
                int thisUid = Integer.valueOf(item);
                // 删除之前，要判断删除的数据中不包含当前登录的用户
                if (uid == thisUid) {
                    return 0;
                }
                idsList.add(thisUid);
            }
        }
        int result = userService.dels(idsList);
        System.out.println("删除多条数据结果：" + result);
        return result;
    }
}
